﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using HT.Service;
using HT.Persistency;
using HT.Model;
using HT.Workflow;
using System.Workflow.Runtime.Hosting;
using System.Workflow.ComponentModel;



namespace HT.Business
{
    public class WorkflowEngine
    {
        private static WorkflowEngine workflowEngineInstance = null;
        private WorkflowRuntime workflowRuntime = null;

        private IReimbursementService reimbursementService = null;

        private WorkflowEngine()
        {
            workflowRuntime = new WorkflowRuntime();

            //加载通讯服务
            ExternalDataExchangeService dataService = new ExternalDataExchangeService();
            workflowRuntime.AddService(dataService);
            reimbursementService = new ReimbursementServiceImpl();
            dataService.AddService(reimbursementService);

            //加载持久化服务
            SqlWorkflowPersistenceService sqlWorkflowPersistenceService =
                new SqlWorkflowPersistenceService(ReimbursementPersistency.connectionString);
            workflowRuntime.AddService(sqlWorkflowPersistenceService);

            //相应流程事件
            workflowRuntime.WorkflowIdled += OnWorkflowIdled;
            workflowRuntime.WorkflowStarted += OnWorkflowStarted;
            workflowRuntime.WorkflowTerminated += OnWorkflowTerminated;
            workflowRuntime.WorkflowCompleted += OnWorkflowCompleted;


            //加载跟踪服务
            //SqlTrackingService sqlTrackingService = new SqlTrackingService(DBAccess.connectionString);
            //sqlTrackingService.IsTransactional = false;
            //workflowRuntime.AddService(sqlTrackingService);

            workflowRuntime.StartRuntime();

            //加载持久化的工作流
            if (workflowRuntime.GetService<SqlWorkflowPersistenceService>().GetAllWorkflows() == null)
                return;           

            foreach (SqlPersistenceWorkflowInstanceDescription desc in workflowRuntime.GetService<SqlWorkflowPersistenceService>().GetAllWorkflows())
            {
                Guid guid = desc.WorkflowInstanceId;
                
                workflowRuntime.GetWorkflow(guid);
            }

            int x = workflowRuntime.GetLoadedWorkflows().Count;
        }

        /// <summary>
        /// 获取工作流引擎实例
        /// </summary>
        public static WorkflowEngine GetWorkflowEngineInstance()
        {
            if (workflowEngineInstance == null)
            {
                workflowEngineInstance = new WorkflowEngine();
            }
            return workflowEngineInstance;
        }

        /// <summary>
        /// 启动一个新的工作流实例
        /// </summary>
        public Guid CreateWorkflow(Type workflowType, Dictionary<string, object> inputParameters)
        {
            WorkflowInstance workflowInstance = null; 

            if (inputParameters == null)
            {
                workflowInstance = workflowRuntime.CreateWorkflow(workflowType);
            }
            else
            {
                workflowInstance = workflowRuntime.CreateWorkflow(workflowType, inputParameters);
            }

            workflowInstance.Start();        
            
            return workflowInstance.InstanceId;
        }

        /// <summary>
        /// 根据工作流Id获得工作流实例
        /// </summary>
        public WorkflowInstance GetWorkflowByInstanceID(Guid instanceId)
        {            
            return workflowRuntime.GetWorkflow(instanceId);
        }

        /// <summary>
        /// 获取工作流运行时
        /// </summary>
        public WorkflowRuntime GetWorkflowRuntime()
        {
            return workflowRuntime;
        }


        private static void OnWorkflowIdled(object sender, WorkflowEventArgs e)
        {
            e.WorkflowInstance.TryUnload();
        }

        private static void OnWorkflowStarted(object sender, WorkflowEventArgs e)
        {
            //SetWorkflowState(e.WorkflowInstance.InstanceId, WorkflowStatus.Running);
        }

        private static void OnWorkflowTerminated(object sender, WorkflowEventArgs e)
        {
            SetWorkflowState(e.WorkflowInstance.InstanceId, WorkflowStatus.Terminated);
        }

        private static void OnWorkflowCompleted(object sender, WorkflowEventArgs e)
        {
            SetWorkflowState(e.WorkflowInstance.InstanceId, WorkflowStatus.Completed);
        }

        /// <summary>
        /// 设置工作流状态，比如：Running，Complete
        /// </summary>
        private static void SetWorkflowState(Guid instanceId, WorkflowStatus workflowStatus)
        {           
                ReimbursementPersistency reimbursementPersistency = new ReimbursementPersistency();
                ReimbursementInfo reimbursementInfo = reimbursementPersistency.GetReimbursementInfoByInstanceID(instanceId);
                reimbursementInfo.Status = workflowStatus.ToString();
                reimbursementPersistency.updateReimbursementInfo(reimbursementInfo);            
            
            
        }

    }
}
